/*
 *    Copyright (c) 2018-2025, 云集汇通 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yunjihuitong.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 */

package com.yjht.common.func.shiro;

import lombok.AllArgsConstructor;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author lengleng
 * @date 2018/6/11
 */
@AllArgsConstructor
public class RedisCache<K, V> implements Cache<K, V> {
    /**
     * cache 前缀
     */
    private static final String CACHE_PREFIX = "shiro:cache:";


    /**
     * 缓存的超时时间，单位为s
     */
    private long expireTime = 120;

    private RedisTemplate<K, V> redisTemplate;

    @Override
    public V get(K key) throws CacheException {
        return redisTemplate.opsForValue().get(CACHE_PREFIX + key);
    }

    /**
     * 将权限信息加入缓存中
     */
    @Override
    public V put(K key, V value) throws CacheException {
        redisTemplate.opsForValue().set((K) (CACHE_PREFIX + key), value, this.expireTime, TimeUnit.SECONDS);
        return value;
    }

    /**
     * 将权限信息从缓存中删除
     */
    @Override
    public V remove(K key) throws CacheException {
        V v = redisTemplate.opsForValue().get(CACHE_PREFIX + key);
        redisTemplate.opsForValue().getOperations().delete((K) (CACHE_PREFIX + key));
        return v;
    }

    @Override
    public void clear() throws CacheException {

    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<K> keys() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

}